using BuildingBlocks.Application.Messaging;
using BuildingBlocks.Domain;
using BuildingBlocks.Application.Authentication;
using Ordering.Application.Abstractions.Persistence;
using Ordering.Application.Orders.Contracts;

namespace Ordering.Application.Orders.GetOrders;

internal sealed class GetOrdersQueryHandler(IOrderRepository repository, ICurrentUser currentUser)
    : IQueryHandler<GetOrdersQuery, IReadOnlyCollection<OrderResponse>>
{
    public async ValueTask<Result<IReadOnlyCollection<OrderResponse>>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
    {
        var orders = await repository.GetByUserIdAsync(currentUser.UserId, cancellationToken);

        IReadOnlyCollection<OrderResponse> response = orders
            .Select(order => order.ToResponse())
            .ToArray();

        return Result.Success(response);
    }
}
